package com.jspica.app.messagespam;

import java.sql.SQLException;
import java.util.*;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.*;
import android.database.Cursor;
import android.net.*;
import android.os.Bundle;
import android.telephony.*;
import android.util.*;
import android.view.*;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.*;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.CompoundButton.OnCheckedChangeListener;

import com.jspica.app.messagespam.R;
import com.jspica.app.messagespam.BlockedListDAO;
import com.jspica.app.messagespam.MyCursorAdapter;

public class WhiteList extends Activity {

	private ListView keywordList;
	private EditText txtKeyword;
	private Cursor cursor;
	private Button btnAdd;
	//private Button btnDel = null;
	//private TextView tv = null; /* 클릭핸들러 함수에서 사용하기 위해 전역으로함. 다른방법있을듯 */
	
	//private ListView blockedList;
	//private Spinner sortNameList;
	//private Button btnDeleteAll;
	//private Button btnRestore;
	//private CheckBox chkAll;

	//String sortField = "time";
	private int selected_id;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.keywordlist);
		
		
		setTitle(getResources().getString(R.string.app_name) + " - " +
			getResources().getString(R.string.set_whitelist));
		
		initiateMembers();
		setEventHandlers();
		registerForContextMenu(keywordList);
		
		//Log.e("regisert","count :" + keywordList.getChildCount());
		
	}

	@Override
	protected void onResume() {
		super.onResume();
		populateList();
		//setEventHandlers();
		//Log.e("resume","count :" + keywordList.getChildCount());
	}

	
	
	/**
	 * 검색조건에 맞는 신용카드 사용 내역을 조회하여 어뎁터로 할당한다.
	 * @throws SQLException 
	 */
	private void populateList() {

		releaseResources();

		ListAdapter adapter;
		BlockedListDAO manager = new BlockedListDAO(getBaseContext());
		try {
			cursor = manager.getWhitelist();
		} catch (SQLException e) {}
		
		startManagingCursor(cursor);

		adapter = new MyCursorAdapter(this, R.layout.keywordrow, cursor, new String[] {"_id", "keyword"}, 
				new int[] {R.id._id, R.id.viewKeyword});

		//Log.e("@@@@@@@@@@@@@@@#1","count :" + adapter.getCount());
		keywordList.setAdapter(adapter);
		
		keywordList.setOnItemClickListener(itemClick);
		//keywordList.setOnLongClickListener((OnLongClickListener) itemLongClick);

		//Log.e("@@@@@@@@@@@@@@@#2","count :" + keywordList.getAdapter().getCount());
		//Log.e("@@@@@@@@@@@@@@@#3","count :" + keywordList.getChildCount());
		
		//keywordList.getAdapter().getItem(0);
		
		/*
		Button test = (Button)keywordList.getChildAt(0).findViewById(R.id.btnDel);
		
		if (test == null) {
			Log.e("@@@@@@@@@@@@@@","testbtnDel NUll");
		} else {
			Log.e("@@@@@@@@@@@@@@","testbtnDel is");
		}
		*/
		
		
		
		/*
		keywordList.setOnClickListener(new OnItemClickListener () {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, log arg3) {
				
				
			}			
		});
		*/
		
		
		
		manager.close();
		manager = null;
		
		//setEventHandlers();
	}
	
	
	AdapterView.OnItemClickListener itemClick = new AdapterView.OnItemClickListener() {
		public void onItemClick(AdapterView parent, View view, int position, long id) {
			// 버튼이 아닌 아이템 클릭시 이벤트임....
			//Log.e("@@@@@@@@@@@@@@","clickecd");
			
			TextView textview = (TextView)view.findViewById(R.id._id);
			selected_id = Integer.parseInt((String)textview.getText());
						
			new AlertDialog.Builder(WhiteList.this)
			.setTitle(getResources().getString(R.string.confirm))
			.setMessage(getResources().getString(R.string.do_delete))
			.setCancelable(false) // Back버튼 작동안하도록.
			.setPositiveButton(getResources().getString(R.string.yes),
				new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
												
					BlockedListDAO dao = new BlockedListDAO(getBaseContext());
					dao.deleteWhitelist(selected_id);
					dao.close();
					populateList();
				}			
			})
			.setNegativeButton(getResources().getString(R.string.no), null)
			.show();
		}
	};
	
	/*
	AdapterView.OnItemLongClickListener itemLongClick = new AdapterView.OnItemLongClickListener() {
		public boolean onItemLongClick(AdapterView parent, View view, int position, long id) {
			// 버튼이 아닌 아이템 클릭시 이벤트임....
			Log.e("@@@@@@@@@@@@@@","clickecd");
			return true;
		}
	};
	*/
	
	
	private void releaseResources() {
		if (cursor != null) {
			cursor.close();
			cursor = null;
		}
	}

	/**
	 * 레이어웃의 요소들을 가져와 멤버변후에 바인딩 시킨다.
	 */
	private void initiateMembers() {
		keywordList = (ListView)findViewById(R.id.keywordList);
		txtKeyword = (EditText)findViewById(R.id.txtKeyword);
		btnAdd = (Button)findViewById(R.id.btnAdd);
		
		/*
		btnDel = (Button)keywordList.f
		if (btnDel == null) {
			Log.e("@@@@@@@@@@@@@@","btnDel NUll");
		} else {
			Log.e("@@@@@@@@@@@@@@","btnDel is");
		}
		*/
		
		//blockedList = (ListView)findViewById(R.id.blockedList);
		//btnDeleteAll = (Button)findViewById(R.id.deleteAll);
		//btnRestore = (Button)findViewById(R.id.restore);
		//chkAll = (CheckBox)findViewById(R.id.checkAll);
	}

	/* 리스트에 대한 리스너를 등록한다. */
	/*
	@Override
	public boolean onContextItemSelected(MenuItem selectedContextItem) {
		AdapterContextMenuInfo selectedMenuInfo = (AdapterContextMenuInfo)selectedContextItem.getMenuInfo();
		final Cursor cursor = (Cursor)keywordList.getItemAtPosition(selectedMenuInfo.position);

		if (selectedContextItem.getItemId() == 0) { // 삭제하기
			BlockedListDAO dao = new BlockedListDAO(getBaseContext());
			dao.deleteRow(cursor.getInt(cursor.getColumnIndex("_id")));
			dao.close();
			populateList();
		}
		return true;
	}
	*/

	/*
	public boolean onContextItemSelected(MenuItem selectedContextItem) {
		Log.e("onContextItem","count :" + keywordList.getChildCount());
		
		AdapterContextMenuInfo selectedMenuInfo = (AdapterContextMenuInfo)selectedContextItem.getMenuInfo();
		final Cursor cursor = (Cursor)blockedList.getItemAtPosition(selectedMenuInfo.position);

		if (selectedContextItem.getItemId() == 0) { // 삭제하기
			BlockedListDAO smsListDao = new BlockedListDAO(getBaseContext());
			smsListDao.deleteRow(cursor.getInt(cursor.getColumnIndex("_id")));
			populateList();
		}
		
		return true;
		
	}
	*/
	
	
	
	
	
	
	/**
	 * 버튼들에 대한 클릭 이벤트 리스너를 등록한다.
	 */
	private void setEventHandlers() {
		btnAdd.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String keyword = txtKeyword.getText().toString().trim();
				//Log.e("@@@@1", "keyword :" + keyword);
				if (!keyword.equals("")) {
					//Log.e("@@@@2", "keyword :" + keyword);
					BlockedListDAO dao = new BlockedListDAO(getBaseContext());
					dao.insertWhitelist(keyword);
					dao.close();
					populateList();
				}
			}
		});
		
		/*		
		btnDel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Log.e("@@@@OKOKOKOKOKOKKOKKO", "keyword :");
			}
		});
		*/
		
		/*
		Button bt = null;
		Log.e("##############","count :"+keywordList.getChildCount());
		for (int i = 0; i < keywordList.getChildCount(); i++) {
					
			bt = (Button)keywordList.getChildAt(i).findViewById(R.id.btnDel);
			//tv = (TextView)keywordList.getChildAt(i).findViewById(R.id._id);
						
			bt.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Log.e("##############","@@@@@@@@@@@@@@@2");
					BlockedListDAO dao = new BlockedListDAO(getBaseContext());
					TextView tv = (TextView)v.findViewById(R.id._id);
					dao.deleteWhitelist(tv.getText().toString());
					dao.close();
					//populateList();
				}
			});
		}
		*/
	
		/*
		btnDeleteAll.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				new AlertDialog.Builder(WhilteList.this)
				.setTitle(getResources().getString(R.string.confirm))
				.setMessage(getResources().getString(R.string.do_delete))
				.setCancelable(false) // Back버튼 작동안하도록.
				.setPositiveButton(getResources().getString(R.string.yes),
					new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
												
						BlockedListDAO smsListDao = new BlockedListDAO(getBaseContext());
						//smsListDao.deleteAll();
						
						CheckBox cb = null;
						
						for (int i = 0; i < blockedList.getChildCount(); i++) {
							cb = (CheckBox)blockedList.getChildAt(i).findViewById(R.id.check);
							
							if (cb.isChecked()) {
								TextView view = (TextView)blockedList.getChildAt(i).findViewById(R.id._id);
								//Log.e("STring@@@@@@@@@@@@@@", (String)view.getText());
								
								smsListDao.deleteRow(Integer.parseInt((String)view.getText()));
							}
						}
									
						//adapter.getItem(position);
						
						//Log.e("@@@@2count@@@@@@@@@", "len: " + adapter.getCount());
						
						smsListDao.close();
						populateList();
						
						
						
					}			
				})
				.setNegativeButton(getResources().getString(R.string.no), null)
				.show();
			}
		});
		
		chkAll.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				
				CheckBox cb = null;
				
				for (int i = 0; i < blockedList.getChildCount(); i++) {
					cb = (CheckBox)blockedList.getChildAt(i).findViewById(R.id.check);
					cb.setChecked(isChecked);
				}
			}
		});
		*/
	}
	
}